<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="学生姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学号" prop="studentNum">
        <el-input
          v-model="queryParams.studentNum"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        v-if="!propsInfo && $store.getters.roleId != 'branchAdmin'"
        :label="`${$branchName ? $branchName : '分院'}`"
        prop="branchId"
      >
        <el-select
          filterable
          @change="branchChange(queryParams.branchId)"
          v-model="queryParams.branchId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in queryParams_branchs"
            :key="index"
            :label="item.branchName"
            :value="parseInt(item.branchId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="!propsInfo"
        :label="`${$majorName ? $majorName : '专业'}`"
        prop="majorId"
      >
        <el-select
          filterable
          @change="majorChange(queryParams.majorId)"
          v-model="queryParams.majorId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in queryParams_majors"
            :key="index"
            :label="item.majorName"
            :value="parseInt(item.majorId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="!propsInfo"
        label="行政班"
        prop="classId"
      >
        <el-select
          filterable
          v-model="queryParams.classId"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="(item, index) in queryParams_classes"
            :key="index"
            :label="item.className"
            :value="parseInt(item.classId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          filterable
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
        >
          <el-option label="全部" :value="''"></el-option>
          <el-option label="停用" :value="1"></el-option>
          <el-option label="启用" :value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-preventReClick
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button
          v-preventReClick
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleSwitch('all')"
        >批量停用
        </el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
          <el-button v-preventReClick
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:post:export']"
          >导出</el-button>
        </el-col> -->
      <el-col :span="1.5">
        <el-upload
          multiple
          :http-request="handleImport"
          :show-file-list="false"
          action="#"
          accept=".xls,.xlsx"
          ref="upload"
        >
          <el-button
            v-preventReClick
            type="warning"
            plain
            icon="el-icon-folder-add"
            size="mini"
          >导入
          </el-button
          >
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-preventReClick
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleTemplate"
        >下载模板
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      height="536"
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column fixed type="selection" width="55" align="center"/>
      <el-table-column
        fixed
        label="学号"
        width="100"
        show-overflow-tooltip
        align="center"
        prop="studentNum"
      />

      <el-table-column
        fixed
        label="姓名"
        width="100"
        show-overflow-tooltip
        align="center"
        prop="name"
      />
      <el-table-column
        show-overflow-tooltip
        label="分院"
        align="center"
        prop="branchName"
      />
      <el-table-column
        show-overflow-tooltip
        label="专业"
        align="center"
        prop="majorName"
      />
      <el-table-column
        show-overflow-tooltip
        label="行政班"
        align="center"
        prop="className"
      />
      <el-table-column width="60" label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          {{ scope.row.sex == 0 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column width="150" label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            @change="handleSwitch(scope.row)"
            :active-value="0"
            :inactive-value="1"
            :value="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-preventReClick
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button slot="reference" type="text" size="mini"
              >更多<i class="el-icon-arrow-down"></i
              ></el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <div @click="handleUpdate(scope.row)">
                  <el-button
                    v-preventReClick
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                  >
                    编辑
                  </el-button>
                </div>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  v-preventReClick
                  size="mini"
                  type="text"
                  icon="el-icon-refresh"
                  @click="handleReset(scope.row)"
                >
                  重置密码
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <div @click="handleDelete(scope.row)">
                  <el-button
                    v-if="scope.row.status == 1"
                    v-preventReClick
                    size="mini"
                    type="text"
                    style="color: #e95756"
                    icon="el-icon-delete"
                  >删除
                  </el-button
                  >
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改岗位对话框 -->
    <updateStudentDialog :open.sync="open" :openType="openType" :propsInfo="propsInfo" :studentForm="studentForm"
                         @refresh="getList"
    ></updateStudentDialog>
  </div>
</template>

<script>
import {
  listPost_branch,
  listPost_major,
  listPost_class
} from '@/api/schoolOrganization/organization'
import {
  addPost_changeStatus,
  addPost_resetPwd,
  listPost_student,
  delPost_student,
  checkStudentNum,
  import_student
} from '@/api/schoolOrganization/student'
import updateStudentDialog from './components/updateStudentDialog'

export default {
  name: 'Student',
  dicts: ['sys_normal_disable'],
  components: {
    updateStudentDialog
  },
  props: {
    propsInfo: {
      type: [Object],
      default: null
    }
  },
  data() {
    return {

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 是否显示弹出层
      open: false,
      openType: 1,
      studentForm: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: '',
        name: '',
        branchId: '',
        majorId: '',
        classId: '',
        studentNum: ''
      },
      //   分院列表
      queryParams_majors: [],
      queryParams_classes: [],
      queryParams_branchs: []
    }
  },
  watch: {
    propsInfo: {
      handler() {
        if (this.propsInfo) {
          this.queryParams.classId = this.propsInfo.classId
        }
        if (this.$store.getters.roleId != 'branchAdmin') {
          this.getBranch()
        } else {
          this.queryParams.branchId = this.$store.getters.branchId
          this.branchChange(this.queryParams.branchId)
        }
        this.getList()
      },
      deep: true,
      immediate: true
    }
  },
  created() {

  },
  methods: {
    handleTemplate() {
      window.location.href = '/static/stu.xlsx'
    },
    async handleImport(file) {
      let formData = new FormData()
      formData.append('file', file.file)
      const loading = this.$loading({
        lock: true,
        text: '正在上传,请稍等…',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.6)'
      })
      import_student(formData).then(() => {
        loading.close()
        this.$modal.msgSuccess('导入成功')
        this.getList()
      }).catch(() => {
        loading.close()
      })
    },
    handleDetail(row) {
      this.$router.push({
        path: '/schoolOrganization/studentDetail',
        query: {
          studentId: row.studentId
        }
      })
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.studentForm = row
      this.open = true
      this.openType = 2
    },
    async branchChange(val) {
      this.queryParams.classId = ''
      this.queryParams_classes = []
      this.queryParams.majorId = ''
      let response = await listPost_major({
        pageNum: 1,
        pageSize: 999,
        branchId: val
      })
      if (val) {
        this.queryParams_majors = response.rows
      } else {
        this.queryParams_majors = []
      }

    },
    async majorChange(val) {
      this.queryParams.classId = ''
      let response = await listPost_class({
        pageNum: 1,
        pageSize: 999,
        majorId: val
      })
      if (val) {
        this.queryParams_classes = response.rows
      } else {
        this.queryParams_classes = []
      }
    },
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId
      }).then((response) => {
        this.queryParams_branchs = response.rows
      })
    },
    /** 查询岗位列表 */
    getList() {
      this.loading = true
      if (this.propsInfo) {
        this.queryParams.classId = this.propsInfo.classId
      }
      // 如果url带班级id
      listPost_student(this.queryParams).then((response) => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.studentId)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      const loading = this.$loading({
        lock: true,
        text: '正在查询学生容量...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.6)'
      })
      try {
        let res = await checkStudentNum()
        if (res.data) {
          this.open = true
          this.openType = 1
        } else {
          this.$modal.msgWarning('当前已达到学生数量限制')
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.studentId || this.ids
      this.$modal.confirm('是否确认删除？').then(async() => {
        const loading = this.$loading({
          lock: true,
          text: '删除中…',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)'
        })
        try {
          let res = await delPost_student(postIds)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('删除成功')
            this.getStudentList()
          }
        } catch (e) {
          console.error(e)
        } finally {
          loading.close()
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    handleReset(row) {
      const postIds = row.studentId
      this.$modal.confirm('是否确认重置密码？').then(async() => {
        const loading = this.$loading({
          lock: true,
          text: '重置密码中…',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)'
        })
        try {
          let res = await addPost_resetPwd(postIds)
          const { code } = res
          if (code == 200) {
            this.$modal.msgSuccess('重置密码成功')
            this.getList()
          }
        } catch (e) {
          console.error(e)
        } finally {
          loading.close()
        }
      }).catch(() => {
        this.$modal.msgInfo('已取消')
      })
    },
    handleSwitch(row) {
      let newstatus
      const postIds = row.studentId || this.ids
      if (row !== 'all') {
        if (row.status == 0) {
          this.$confirm(
            `停用后，学生会退出所在班级，并清空全部学习中记录，是否确认停用?`,
            '停用确认',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
            .then(async() => {
              newstatus = 1
              this.changeStatus(postIds, newstatus)
            })
            .catch(() => {
              this.$modal.msgInfo('已取消')
            })
        } else {
          newstatus = 0
          this.changeStatus(postIds, newstatus)
        }
      } else {
        newstatus = 1
        this.$confirm(
          '停用后，学生会退出所在班级，并清空全部学习中记录，是否确认批量停用？',
          '批量停用确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          this.changeStatus(postIds, newstatus)
        }).catch(() => {
          this.$modal.msgInfo('已取消')
        })
      }
    },
    async changeStatus(postIds, newstatus) {
      let formData = new FormData()
      formData.append('studentIds', postIds)
      formData.append('status', newstatus)
      let loading = this.$loading({
        lock: true,
        text: '修改中…',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.3)'
      })
      try {
        let res = await addPost_changeStatus(formData)
        const { code } = res
        if (code == 200) {
          this.$modal.msgSuccess('修改状态成功')
          this.getList()
        }
      } catch (e) {
        console.error(e)
      } finally {
        loading.close()
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', { ...this.queryParams }, `post_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.uploadTip {
  height: 210px;
  line-height: 390px;
}

.upload-head {
  width: 152px;
  height: 212px;

  .add {
    width: 29px;
    height: 29px;
    margin: 70px 0 0 0;
  }

  .cover {
    width: 150px;
    height: 210px;
    border-radius: 4px;
  }
}

.upload-head:hover:after {
  line-height: 210px;
}
</style>
